package com.web.daonila.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.web.daonila.service.CoreService;
import com.web.daonila.util.SignUtil;


@Controller
public class WeiPingServlet{
	
   @Autowired
   private CoreService coreService;
	
   @RequestMapping(value = "weiping",method={RequestMethod.GET})
   public void doGet(HttpSession session, HttpServletRequest req,HttpServletResponse resp) throws IOException {
	// 微信加密签名  
       String signature = req.getParameter("signature");  
       // 时间戳  
       String timestamp = req.getParameter("timestamp");  
       // 随机数  
       String nonce = req.getParameter("nonce");  
       // 随机字符串  
       String echostr = req.getParameter("echostr");  
 
       PrintWriter out = resp.getWriter();  
       // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败  
       if (SignUtil.checkSignature(signature, timestamp, nonce)) {  
           out.print(echostr);  
       }  
       out.close();  
       out = null;  
   }

   /** 
    * 处理微信服务器发来的消息 
    */ 
   @RequestMapping(value = "weiping",method={RequestMethod.POST})
   public void doPost(HttpSession session, HttpServletRequest req,HttpServletResponse resp) throws IOException {
	// 将请求、响应的编码均设置为UTF-8（防止中文乱码）  
	   req.setCharacterEncoding("UTF-8");  
	   resp.setCharacterEncoding("UTF-8");  
 
       // 调用核心业务类接收消息、处理消息  
       String respMessage = coreService.processRequest(req);  
         
       // 响应消息  
       PrintWriter out = resp.getWriter();  
       out.print(respMessage);  
       out.close();  
	}
}
